package org.activemonitoring.datastore.jms;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.activemonitoring.datastore.DataStore;
import org.activemonitoring.domain.Measures;
import org.apache.log4j.Logger;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

public class MeasuresMessageListener implements MessageListener {

    private static final Logger logger = Logger.getLogger(MeasuresMessageListener.class);

    @Resource
    private MessageConverter messageConverter;
    private DataStore dataStore;

    @Override
    public void onMessage(Message message) {
        logger.debug("Received a jms message");
        try {
            Measures measures = (Measures) this.messageConverter.fromMessage(message);
            if (logger.isDebugEnabled()) {
                logger.debug("Message contains " + measures.getMeasure().size() + " measures");
            }
            this.dataStore.store(measures);
        } catch (MessageConversionException e) {
            logger.error("Error while converting message content", e);
        } catch (JMSException e) {
            logger.error("Error while handling message", e);
        }
    }

    public void setMessageConverter(MessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }

    public void setDataStore(DataStore dataStore) {
        this.dataStore = dataStore;
    }
}
